<!-- 我的客户 -->
<template>
  <div  class="dashboard-editor-container">
    <el-row class="main-el-row" style="background: #fff; padding: 16px 16px;">
        <div class="top topSubmitBtn">
          <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addResources()">添加客户</el-button>
          <!-- <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addgroupdialog()">添加分组</el-button> -->
        </div>
        <!-- <div class="btn">
          <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addResources()">添加任务</el-button>
        </div> -->
        <div class="xxx" style="display:flex;justify-content:space-between;margin-top: 30px;">
          <div class="lefttree" style="height:calc(100vh - 86px);">
            <!-- <div class="tabclick">
              <div class="tabitem" @click="handleClick()">
                <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
              </div>
            </div> -->
            <!-- icon-class="el-icon-arrow-right"  -->
            <el-tree 
              v-show="tab" 
              node-key="ID" 
              :data="CustomerList" 
              :expand-on-click-node=false 
              :props="defaultProps" 
              @node-click="handleNodeClick"  
              :default-expanded-keys="[1]" 
              highlight-current
              style="width:200px;">
              <span slot-scope="{ node }" class="custom-tree-node">
                <span>
                  <!-- <i class="el-icon-folder-opened" style="margin-right: 10px;" /> -->
                  <svg-icon v-show="node.level === 1" icon-class="peoples" style="margin-right: 10px;"/>
                  <svg-icon v-show="node.level === 2" icon-class="user" style="margin-right: 10px;"/>
                  <span class="tree-text">{{ node.label }}</span>
                </span>
              </span>
            </el-tree>
            <!-- :render-content="renderContent" -->
          </div>
          <div style="width:calc(100% - 240px)">
            <el-table 
              border 
              height="580px"
              :data="tableData" 
              style="width:100%" >
              <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
              <el-table-column label="客户分组" width="120" prop="BelongGroup" align="left"></el-table-column>
              <el-table-column label="企业名称" prop="CorpName" align="left" width="150px" show-overflow-tooltip></el-table-column>
              <el-table-column label="联系人" prop="Name" align="left" width="120px" show-overflow-tooltip></el-table-column>
              <el-table-column label="用户类型" prop="Type" align="left" show-overflow-tooltip></el-table-column>
              <el-table-column label="联系邮箱" prop="Account" align="left" width="180px" show-overflow-tooltip></el-table-column>
              <el-table-column label="电话" prop="Mobile" align="left" show-overflow-tooltip></el-table-column>
              <el-table-column label="录入时间" prop="TransTime" align="left" show-overflow-tooltip></el-table-column>
              <el-table-column label="员工名称" align="left" width="180px" show-overflow-tooltip>
                <template slot-scope="{row}">
                  <span><span>{{row.EmployeeName}} [{{row.Department}}]</span></span>
                </template>
              </el-table-column>
              <el-table-column label="备注" prop="Descp" align="left" show-overflow-tooltip></el-table-column>
              <el-table-column label="操作" align="left" width="150px" fixed="right">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary" @click="changeMailGlobal(scope.row)">修改</el-button>
                  <el-button size="mini" type="danger" @click="deleteMailGlobal(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination 
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" 
              :current-page=pageNum
              :page-size=pageSize
              background 
              layout="total, prev, pager, sizes, next, jumper"
              :total="total">
            </el-pagination>
          </div>
        </div>
    </el-row>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape=false
      title="添加分组"
      :visible.sync="groupdialog"
      v-el-drag-dialog
      width="30%">
      <el-form label-width="100px" :model="grouForm" :rules="rule2" ref="departForm">
        <el-form-item label='上级分组:'>
          <el-cascader
            ref="clientgroup"
            style="width:100%;"
            v-model="grouForm.lastDepartmemt"
            placeholder="请选择分组，若空则为根分组"
            clearable
            :show-all-levels="false"
            :options="CustomerList"
            :props="{ expandTrigger: 'hover', checkStrictly: true, label: 'DepartmentName', value: 'DepartmentName'}"
            @visible-change="groupOnlick"
            @expand-change="groupOnlick"
            >
          </el-cascader>
        </el-form-item>
        <el-form-item label='分组名称:' prop="DepartmentName">
          <el-input v-model="grouForm.DepartmentName" maxlength="16"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addgroup()">确 定</el-button>
        <el-button type="info" @click="groupdialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape=false
      :title="Action === 1 ? '添加客户' : '修改客户' "
      :visible.sync="dialogVisible"
      v-el-drag-dialog
      width="30%">
      <el-form label-width="100px" :model="resourceForm" :rules="rules" ref="resourceForm">
        <el-form-item label='所属分组:' prop="BelongGroup">
          <el-cascader
            ref="cascaderAddr"
            style="width:100%;"
            v-model="resourceForm.BelongGroup"
            placeholder="请选择分组"
            clearable
            :options="CustomerList"
            :props="{ expandTrigger: 'hover', label: 'DepartmentName', value: 'DepartmentName'}"
            @change="handleChange"
            >
          </el-cascader>
        </el-form-item>
        <el-form-item label='企业名称:' prop="CorpName">
          <el-input v-model="resourceForm.CorpName" maxlength="32"></el-input>
        </el-form-item>
        <el-form-item label='联系人:' prop="Name">
          <el-input v-model="resourceForm.Name"  maxlength="16"></el-input>
        </el-form-item>
        <el-form-item label='用户类型:' prop="Type">
          <el-select v-model="resourceForm.Type"  maxlength="16" style="width:100%" placeholder="请选择用户类型"> 
            <el-option value="潜在客户" label="潜在客户"></el-option>
            <el-option value="重要客户" label="重要客户"></el-option>
            <el-option value="成交客户" label="成交客户"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label='联系邮箱:' prop="Account">
          <el-input v-model="resourceForm.Account"  maxlength="32" :disabled="Action!==1"></el-input>
        </el-form-item>
        <el-form-item label='电话:' prop="Mobile">
          <el-input v-model="resourceForm.Mobile"  oninput ="value=value.replace(/[^0-9-]/g,'')"  maxlength="13"></el-input>
        </el-form-item>
        <!-- <el-form-item label='区域:' prop="Area">
          <el-input v-model="resourceForm.Area"  maxlength="32"></el-input>
        </el-form-item> -->
        <el-form-item label='备注:' prop="Descp">
          <el-input v-model="resourceForm.Descp" type="textarea" :rows="3" maxlength="64"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { connrequest } from '@/api/firstPage'
import Cookies from 'js-cookie'
import { getTreeData, ParamDictURLtype, parseTime } from '@/utils/index.js'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
directives: { elDragDialog },
data() {
  return {
    pageNum: 1,
    pageSize: 10,
    total: 10,
    tab: true,
    tableData: [],
    emailForm: {},
    emailList: [],
    choseDepartList: [],
    dialogVisible: false,
    groupdialog: false,
    grouForm: {},
    rules: {
      BelongGroup: [
        { required: true, message: "请选择分组"}
      ],
      CorpName: [
        { required: true, message: "请输入企业名称"}
      ],
      Account:[
        { required: true, message: "请输入邮箱"},
        {
          validator: function(rule, value, callback) {
            if (/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i.test(value) == false  && value) {
              callback(new Error("邮箱格式错误"));
            } else {
              callback();
            }
          },
          trigger: "blur"
        }
      ],
      Name:[
        { required: true, message: "请输入客户姓名"}
      ],
      Type:[
        { required: true, message: "请选择用户类型", trigger:'change'}
      ],
      Mobile:[
        {
          validator: function(rule, value, callback) {
            if(/(^(\d{3,4}-)?\d{7,8})$|(13[0-9]{9})/.test(value) == false  && value){
              callback(new Error("电话格式错误"));
            } else {
              callback();
            }
          }
        }
      ]
    },
    rule2:{
      DepartmentName: [
        { required: true, message: '分组名称不能为空' }
      ],
    },
    resourceForm: {},
    Action: 1,
    CustomerList: [],
    allgroupList: [],
    options:[],
    defaultProps:{
      children: 'children',
      label: 'DepartmentName'
    },
  }
},
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = Cookies.get('DefaultPageLength') * 1
    this.GetCustomerClass()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {},
  methods: {
    collapse(list) {
      var _this = this;
      if(list){
        list.forEach(function(child) {
            if (child.expand) {
              child.expand = false;
            }
            child.children && _this.collapse(child.children);
        });
      }
    },
    onExpand(e,data) {
      if ("expand" in data) {
        data.expand = !data.expand;
        if (!data.expand && data.children) {
            this.collapse(data.children);
        }
      } else {
          this.$set(data, "expand", true);
      }
    },
    handleClick() {
      this.tab = !this.tab
    },
    handleSizeChange(pageSize){
      this.pageSize = pageSize
      this.pageNum = 1
      this.getData()
    },
    handleCurrentChange( pageNum ){
      this.pageNum = pageNum
      this.getData()
    },
    renderContent(h, { node, data, store }) {
      return (
      <span class="custom-tree-node">
        <span>{node.label}</span>
        <span>
          <el-button size="mini" type="text" on-click={ () => this.removenode(node, data) }>删除</el-button>
        </span>
      </span>);
    },
    addgroupdialog(){
      this.groupdialog = true;
      this.grouForm = {}
    },
    addgroup(){
      this.$refs['departForm'].validate( async(valid) => {
        if(valid){
          if(this.allgroupList.indexOf(this.grouForm.DepartmentName) !== -1){
            this.$message.error('该分组已经存在')
          }else{
            const data = { 
              Data:{
                DepartmentName: this.grouForm.DepartmentName,
                ParentName: this.$refs['clientgroup'].getCheckedNodes()[0]?.value || ''
              }
            }
            const res = await connrequest('AddCustomerClass', data)
            if(res.Status.StatusCode === 0){
              this.$message({
                type: 'success',
                message: '分组添加成功'
              });
              this.getData()
              this.GetCustomerClass()
              this.groupdialog = false
            }
          }
        }
      })
    },
    // 删除节点
    removenode(node,data){
      if(data.children !== undefined){
        this.$message.error('该分组下还存在其他分组')
      }else{
        let DepartmentName = data.DepartmentName
        this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let data = {
            Data:{
              DepartmentName:DepartmentName,
            }
          }
          const res = await connrequest('DelCustomerClass', data)
          if(res.Status.StatusCode === 0){
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getData()
            this.GetCustomerClass()
            this.groupdialog = false
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      }
    },
    async handleNodeClick(data, node) {
      this.pageNum = 1
      if(data.DepartmentName === '全部客户'){
        this.Group = ''
        this.choseDepartList = []
        this.DepartmentName  = []
      }else{
        this.Group = data.DepartmentName
        const departmentNames = [];
        let currentNode = node;
        while (currentNode) {
          if (currentNode.data.DepartmentName !== undefined) {
            departmentNames.unshift(currentNode.data?.DepartmentName);
          }
          currentNode = currentNode.parent;
        }
        this.choseDepartList = departmentNames
        this.DepartmentName  = departmentNames[departmentNames.length - 1]
        if(!node.isLeaf){
          this.choseDepartList = []
          this.DepartmentName  = []
        }
      }
      this.getData()
    },
    async GetCustomerClass(){
      const res = await connrequest('GetCustomerClass')
      this.xxx = res.Data
      let arr = []
      this.CustomerList = getTreeData(this.treeing(res.Data,'DepartmentName','ParentName'))
      res.Data = res.Data || []
      res.Data.map(item => {
        arr.push(item.DepartmentName)
      })
      this.allgroupList = arr  //所有分组放到数组里
      this.getData()
    },
    treeing(arr, id, parentid) {
      let tree = []
      const map = {}
      for (let item of arr) {
        // 一个新的带children的结构
        let newItem = map[item.DepartmentName] = {
          ...item,
          children: []
        }
        if (map[item.ParentName]) { // 父节点已存进map则在父节点的children添加新元素
          let parent = map[item.ParentName]
          parent.children.push(newItem)
        } else { // 没有父节点，在根节点添加父节点
          tree.push(newItem)
        }
      }
      let newarr = [{DepartmentName:'全部客户',ParentName:'', children:tree}]
      // return tree
      return newarr
    },
    // 级联选项卡点击关闭下拉
    elCascaderOnlick(){
      let that = this;
      setTimeout(function() {
        document.querySelectorAll(".el-cascader-node__label").forEach((el) => {
          el.onclick = function() {
            this.previousElementSibling.click();
            that.$refs.cascaderAddr.dropDownVisible = false;
          };
        });
      }, 100);
    },
    // 级联选项卡点击关闭下拉
    groupOnlick(){
      let that = this;
      setTimeout(function() {
        document.querySelectorAll(".el-cascader-node__label").forEach((el) => {
          el.onclick = function() {
            this.previousElementSibling.click();
            that.$refs.clientgroup.dropDownVisible = false;
          };
        });
      }, 100);
    },
    handleChange(item){
      if(item){
        this.DepartmentName  = item[item.length - 1]
        let Nodearr = this.$refs['cascaderAddr'].getCheckedNodes()[0]
        this.ParentName = Nodearr.level === 1 ? '' : item[item.length - 2]
      }
    },
    addResources(){
      this.Action = 1
      this.resourceForm = {group: this.choseDepartList, BelongGroup: this.choseDepartList}
      this.$nextTick(()=>{
        this.$refs['resourceForm'].clearValidate()
      })
      this.dialogVisible = true
    },
    changeMailGlobal(row){
      const parentNodeArray = [];
      this.findParentNodes(this.CustomerList, row.BelongGroup, parentNodeArray);
      this.Action = 2
      this.$nextTick(()=>{
        this.$refs['resourceForm'].clearValidate()
      })
      this.resourceForm = {...row, group: row.DepartmentName, BelongGroup: parentNodeArray}
      this.DepartmentName  = parentNodeArray[parentNodeArray.length - 1]
      this.dialogVisible = true
    },
    findParentNodes(tree, nodeName, parentArray) {
      if (!tree || !Array.isArray(tree)) {
        return; // 树为空或不是一个数组，直接返回
      }
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.DepartmentName === nodeName) {
          parentArray.unshift(node.DepartmentName); // 找到匹配的节点，将其存储到数组中
          return; // 返回，无需继续查找其他节点
      }
        if (node.children && Array.isArray(node.children)) {
          this.findParentNodes(node.children, nodeName, parentArray); // 递归查找子节点
          if (parentArray.length > 0) {
            parentArray.unshift(node.DepartmentName); // 找到目标节点的父节点，将其存储到数组中
            return; // 返回，无需继续查找其他节点
        }
      }
    }
    },
    deleteMailGlobal(row){
      this.Action = 3
      this.resourceForm = {...row}
      this.$confirm('此操作将删除该客户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const data = {
          Data:{
            Action: this.Action,
            Detail: {
              ...this.resourceForm,
              
            }
          }
        }
        const res = await connrequest('EditCustomer', data)
        if(res.Status.StatusCode === 0){
          this.$message.success('删除成功')
          this.dialogVisible = false
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    async getData() {
      const params = {
        Paging:{
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter:{
          // Account:'',
          // CorpName:'',
          // CustomType:'',
          Group: this.Group
        }
      }
      const res = await connrequest('GetCustomer', params)
      // this.tableData = getTreeData(this.treeing(res.Data))
      res.Data.map(item => {
        item.TransTime = parseTime(item.TransTime)
        return item
      })
      this.tableData = res.Data
      this.total = res.Paging.TotalCount
    },
    ParamDictURLtype(DepartmentName){
      let arr = this.xxx
      let newarr = arr.filter(item => {return item.DepartmentName === DepartmentName})
      return `${newarr[0].ParentName} / ${newarr[0].DepartmentName}`
    },
    submit(){
      this.$refs['resourceForm'].validate(async (valid) => {
        if(valid){
          if(this.Action === 1 && this.tableData.some(item => item.Account === this.resourceForm.Account)){
            this.$message.error('该企业已经存在')
            return false
          }
          if(this.DepartmentName === this.resourceForm.Name){
            this.$message.error('分组和姓名不能相同')
            return false
          }
          delete(this.resourceForm.group)
          const data = {
            Data:{
              Action: this.Action,
              Detail: {
                ...this.resourceForm,
                BelongGroup: this.DepartmentName,
                DepartmentName: this.DepartmentName,
                ParentName: this.ParentName
              }
            }
          }
          const res = await connrequest('EditCustomer', data)
          if(res.Status.StatusCode === 0){
            this.Action === 1 ? this.$message.success('添加成功') : this.$message.success('修改成功')
            this.dialogVisible = false
            this.getData()
          }
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
@import "~@/styles/variables.scss";
@import "./components/css/conncss.scss";
.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.main-el-row{
  height: calc(100vh - 82px)
}
/* 设置垂直滚动条（如果需要水平滚动条，请添加::-webkit-scrollbar-horizontal选择器） */
::-webkit-scrollbar {
    width: 3px; /* 滚动条宽度 */
  }
  /* 滚动条轨道部分（即背景） */
  ::-webkit-scrollbar-track {
    background-color: #fff; /* 背景颜色 */
  }
  /* 滚动条上下两端的按钮 */
  ::-webkit-scrollbar-button {
    display: none; /* 隐藏按钮 */
  }
  /* 滚动条滑块部分（即滑块本身） */
  ::-webkit-scrollbar-thumb {
    background-color: #ccc; /* 滑块颜色 */
  }
.lefttree{
  width: 230px;
  border: 1px solid #ebeef5;
  margin-right: 10px;
  padding: 10px;
  position: relative;
  overflow-y: auto;
  .tabclick{
    transform: rotate(-90deg);
    position: absolute;
    top: calc((100vh - 300px) / 2);
    left: -55px;
    margin-top: 20px;
  }
  ::v-deep .el-tree{
    margin-left: 20px;
    color: #676c70;
    background-color: #ffffff;
    .tree-text{
      font-size: 14px;
      display: inline-block;
      width: 130px;
      white-space: nowrap; /* 禁止换行 */
      overflow: hidden; /* 溢出隐藏 */
      text-overflow: ellipsis; /* 超出部分用省略号表示 */
    }
  }
  ::v-deep.el-tree-node__content{
    &:hover{
      background-color: #cccccc;
    }
  }
  ::v-deep .el-tree-node.is-current > .el-tree-node__content {
    color: #459ffc !important;
    background-color: #f7f7f7 !important;
  }
  // ::v-deep .el-tree-node__expand-icon{
  //   position :absolute;
  //   left: 2%;
  // }
  ::v-deep .el-tree-node__label{
    padding-left: 15px;
  }
}
.content {
  position: relative;
  margin-top: 25px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  ::v-deep .certification{
    .el-form-item{
      margin-bottom: 10px;
    }
    .el-col{
      display: flex;
      align-items: center;
      p{
        width: 100px;
        display:block;
        color: #aaa;
        font-size: 12px;
        padding-left: 20px;
        white-space: nowrap;
      }
    }
  }
}
.top{
  flex-wrap: nowrap;
  margin-bottom: 20px;
}
.btn{
  margin: 20px 0;
}
</style>
<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>